package archer.framework.utils;

import jodd.util.StringUtil;

import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.Iterator;

/**
 * @author christ
 * @date 2015/8/21
 */
public class StringUtils extends StringUtil {

    /**
     * 集合转字符串
     *
     * @param datas
     * @return
     */
    public static String join(Collection<String> datas) {
        return join(datas, ",");
    }

    /**
     * 集合转字符串
     *
     * @param src
     * @param separator
     * @return
     */
    public static String join(Collection<String> src, String separator) {
        if (ValidateUtils.isEmpty(src)) {
            return null;
        }

        Iterator iterator = src.iterator();

        if (!iterator.hasNext()) {
            return "";
        }

        Object first = iterator.next();
        if (!iterator.hasNext()) {
            return first == null ? "" : first.toString();
        }

        StringBuilder result = new StringBuilder();
        if (first != null) {
            result.append(first);
        }

        while (iterator.hasNext()) {
            if (separator != null) {
                result.append(separator);
            }

            Object obj = iterator.next();
            if (obj != null) {
                result.append(obj);
            }
        }

        return result.toString();
    }

    /**
     * 转byte[]
     *
     * @param s
     * @return
     */
    public static byte[] getBytesUtf8(String s) {

        if (ValidateUtils.isEmpty(s)) {
            return null;
        }

        try {
            return s.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * endsWith
     *
     * @param str
     * @param suffix
     * @return
     */
    public static boolean endsWith(String str, String suffix) {
        if (str == null) {
            return false;
        }
        return str.endsWith(suffix);
    }

    /**
     * 加星号
     *
     * @param str
     * @return
     */
    public static String maskMiddle(String str) {

        if (ValidateUtils.isEmpty(str)) {
            return str;
        }

        char[] cs = str.toCharArray();
        if (cs.length == 1) {
            return str;
        }
        if (cs.length == 2) {
            cs[1] = '*';
            return String.valueOf(cs);
        }

        //长度超过3
        int step = cs.length / 3;
        for (int i = step; i <= (cs.length - step - 1); i++) {
            cs[i] = '*';
        }

        return String.valueOf(cs);
    }

}
